package redisjwts

import (
	"KumquatDrivesServices/global"
	"KumquatDrivesServices/jwts"
	"errors"
	"fmt"
	"github.com/go-redis/redis"
	"github.com/sirupsen/logrus"
	"time"
)

func TokenBlack(accessToken, refreshToken string) {
	key1 := fmt.Sprintf("token_black_access%s", accessToken)
	key2 := fmt.Sprintf("token_black_refresh%s", refreshToken)
	claims1, err1 := jwts.ParseToken(accessToken)
	if err1 != nil && !errors.Is(err1, jwts.ErrTokenInvalid) || claims1 == nil {
		logrus.Errorf("accessToken解析失败：%v", err1)
		return
	}
	claims2, err2 := jwts.ParseToken(refreshToken)
	if err2 != nil && !errors.Is(err1, jwts.ErrTokenInvalid) || claims2 == nil {
		logrus.Errorf("refreshToken解析失败：%v", err2)
		return
	}
	second1 := (*claims1.ExpiresAt).Unix() - time.Now().Unix()
	second2 := (*claims2.ExpiresAt).Unix() - time.Now().Unix()
	if err1 = global.Redis.Set(key1, 1, time.Duration(second1)*time.Second).Err(); err1 != nil {
		logrus.Errorf("设置accessToken黑名单失败：%v", err1)
		return
	}
	if err2 = global.Redis.Set(key2, 1, time.Duration(second2)*time.Second).Err(); err2 != nil {
		logrus.Errorf("设置refreshToken黑名单失败：%v", err2)
		return
	}
}
func HasTokenBlack(token ...string) (bool, error) {
	if len(token) == 0 {
		return false, fmt.Errorf("token不能为空")
	}
	var key string
	for _, tokenItem := range token {
		claims, err1 := jwts.ParseToken(tokenItem)
		if err1 != nil && !errors.Is(err1, jwts.ErrTokenInvalid) || claims == nil {
			logrus.Errorf("Token解析失败：值：%s, 错误：%v", tokenItem, err1)
			return false, err1
		}
		switch claims.JwtType {
		case "access":
			key = fmt.Sprintf("token_black_access%s", tokenItem)
		case "refresh":
			key = fmt.Sprintf("token_black_refresh%s", tokenItem)
		default:
			key = ""
		}
	}
	if key == "" {
		return false, fmt.Errorf("token类型不正确")
	}
	if err := global.Redis.Get(key).Err(); err != nil {
		if errors.Is(err, redis.Nil) {
			return true, nil
		}
		logrus.Errorf("获取黑名单失败：%v", err)
		return false, err
	}
	return false, nil
}
